//
//  WBTabBar.swift
//  WeiboSwift
//
//  Created by Apple13 on 16/7/9.
//  Copyright © 2016年 yupeng. All rights reserved.
//

import UIKit


protocol WBTabBarDelegate:NSObjectProtocol {
    func didSelectedComposeButton()
}

class WBTabBar: UITabBar {

    //添加点击按钮的闭包
    var composeButtonclosure: (()->())?
    
    //定义代理对象
    weak var Delegate: WBTabBarDelegate?
    
//MARK: - 懒加载中间的加号按钮
    
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        //添加事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside )
        
        
        //设置图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)


        
        
        button.sizeToFit()
        
        return button
        
    }()
    
    //初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composeButton)
    }
    
    
    //加载xib或者StoryBoard才会调用
    required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
    }
    
    
 //MARK: - "➕"号的点击事件
    
    @objc private func composeButtonAction(){
        
        print("点了一下加号")
        composeButtonclosure?()  //执行闭包
        
//‼️设置代理
        Delegate?.didSelectedComposeButton()
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置按钮的frame
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        //获取系统的控件,比计算控件的宽度
        let itemWidth = width / 5
        
        
        //遍历按钮
        var index = 0
        for value in subviews{
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
            value.x = CGFloat(index) * itemWidth
                value.width = itemWidth
                if index == 1 {
                    index++
                }
            
            index++
            
        }
            
            
        }
        
        
        
    }
    
}
